const {
  default: Toast
} = require("../miniprogram_npm/@vant/weapp/toast/toast");

/*微信小程序双向绑定*/
const updateValue = function (e) {
  let name = e.currentTarget.dataset.inputName;
  this.setData({
    [name]: (e.detail.value || '')
  });
}

/*vant field输入框双向绑定*/
const vantUpdateValue = function (e) {
  e.detail = {
    value: e.detail
  };
  return updateValue.call(this, e);
}

//微信小程序 createSelectorQuery 封装
const elementQuery = function (elements, _this) {
  return new Promise((resolve, reject) => {
    const query = wx.createSelectorQuery().in(_this);
    for (let i = 0; i < elements.length; i++) {
      let {
        el,
        "queryApis": apis
      } = elements[i];
      el = query.select(el);
      for (let j = 0; j < apis.length; j++) {
        el[apis[j]]();
      }
    }
    setTimeout(() => {
      query.exec((res) => {
        resolve(res);
      })
    }, 0)
  })
}


//显示登入授权弹层
const showLoginLayer = function () {
  //存在登入授权组件 弹出授权弹窗
  let page = lastPage(),
    loginLayer = page.selectComponent('.authorize-layer');
  if (loginLayer) {
    loginLayer.setShowLayer({
      currentTarget: {
        dataset: {
          value: true
        }
      }
    });
  }
}

//公用navigateTo跳转
const commonNavigateTo = function (url, params = {}, callback) {
  let app = getApp();
  //未登入禁止跳转页面
  // if (!app.globalData.userLoginState) {
  //   //没有openid
  //   if (!app.globalData.userInfo || !app.globalData.userInfo.openid) {
  //     wx.showLoading({
  //       title: '正在登录',
  //       mask: true
  //     })
  //     app.getOpenId().then((res) => {
  //       //新用户显示登入授权弹层
  //       if (app.globalData.userInfo.isNewUser) {
  //         showLoginLayer();
  //       }
  //     });
  //   } else if (app.globalData.userInfo.isNewUser) {
  //     //新用户显示登入授权弹层
  //     showLoginLayer();
  //   }
  //   return;
  // }
  wx.navigateTo({
    url: url,
    success: (res) => {
      res.eventChannel.emit('data', {
        data: params
      })
      if (callback) {
        callback()
      }
    }
  })
}

//公用多类型跳转
const commonToPage = function (url, toType, params = {}, callback) {
  if (toType == 'navigateTo') {
    commonNavigateTo(url, params, callback);
    return;
  } else {
    wx[toType]({
      url: url,
      success: (res) => {
        if (callback) {
          callback()
        }
      }
    })
  }
}

//获取上一个页面传输的数据
const getPrevPageData = function (_this) {
  return new Promise((resolve, reject) => {
    const eventChannel = _this.getOpenerEventChannel()
    eventChannel.on('data', (resp) => {
      resolve(resp);
    })
  })
}

//将对象序列化
const objSerialize = function (obj) {
  let str = '';
  for (let key in obj) {
    str += `&${key}=${obj[key]}`;
  }
  return str.replace(/^\&/, '');
}

//时间戳转日期格式
const dateFormat = function (timestamp, formats) {
  // formats格式包括
  // 1. Y-m-d
  // 2. Y-m-d H:i:s
  // 3. Y年m月d日
  // 4. Y年m月d日 H时i分
  formats = formats || 'Y-m-d';

  if (timestamp.constructor == String && timestamp.indexOf('-') != -1) {
    timestamp = timestamp.replace(/\-/g, '/')
  }

  var zero = function (value) {
    if (value < 10) {
      return '0' + value;
    }
    return value;
  };

  var myDate = timestamp ? new Date(timestamp) : new Date();

  var year = myDate.getFullYear();
  var month = zero(myDate.getMonth() + 1);
  var day = zero(myDate.getDate());

  var hour = zero(myDate.getHours());
  var minite = zero(myDate.getMinutes());
  var second = zero(myDate.getSeconds());

  return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
    return ({
      Y: year,
      m: month,
      d: day,
      H: hour,
      i: minite,
      s: second
    })[matches];
  });
};

//日期格式转时间戳
const getTimeStamp = function (str) {
  var newstr = str.replace(/-/g, '/');
  var date = new Date(newstr);
  var time_str = date.getTime().toString();
  return date.valueOf();
}

// 当前时间的前N天，前N月，前N年
const getDateDiff = function (dateTimeStamp) {
  var result = '';
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    return "刚刚";
  }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  if (monthC >= 1) {
    result = "" + parseInt(monthC) + "月前";
  } else if (weekC >= 1) {
    result = "" + parseInt(weekC) + "周前";
  } else if (dayC >= 1) {
    result = "" + parseInt(dayC) + "天前";
  } else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前";
  } else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟前";
  } else {
    result = "刚刚";
  }

  return result;
}

//获取最后一个页面
const lastPage = function () {
  let pages = getCurrentPages();
  return pages.length ? pages[pages.length - 1] : null
}

// 获取对应页面
const getQueryUrlPage = function (pageUrl) {
  let pages = getCurrentPages();
  for (let i = 0; i < pages.length; i++) {
    let currPage = pages[i]
    if (currPage.route == pageUrl) {
      return currPage;
      break;
    }
  }
  return null;
}

//获取url参数
const getRequest = function (url) {
  var theRequest = new Object();
  let queryIndex = url.indexOf("?");
  if (queryIndex != -1) {
    var str = url.substr(queryIndex + 1);
    let strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}

// 处理vant weapp Toast.clear 渲染比异步接口慢
const myNextTick = (time = 240) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(true)
    }, time)
  })
}

/**
 * 获取经纬度
 * @param {boolean} isTips 没有授权是否提示框授权
 */
const getLocation = function (isTips = false) {
  return new Promise((resolve, reject) => {
    var defaultData = null,
      //是否开启GPS
      locationEnabled = false;
    var getLocation = () => {
      wx.getLocation({
        type: 'wgs84',
        success: (resp) => {
          resolve(resp);
        },
        fail: (err) => {
          wx.getSystemInfo({
            success(res) {
              locationEnabled = res.locationEnabled;
            }
          })
          if (!locationEnabled) {
            // Toast('未开启GPS定位');
            resolve(defaultData);
          } else {
            //不提示授权
            if (!isTips) {
              resolve(defaultData)
              return;
            }
            //未授权
            wx.showModal({
              title: '位置授权',
              content: '您未授权位置，部分功能将无法使用',
              confirmText: '授权',
              cancelText: '取消',
              success: (res) => {
                if (res.confirm) {
                  wx.openSetting({
                    success: (res) => {
                      if (res.authSetting['scope.userLocation']) {
                        wx.getLocation({
                          type: 'wgs84',
                          success: (resp) => {
                            resolve(resp);
                          },
                          fail: () => {
                            resolve(defaultData)
                          }
                        })
                      } else {
                        resolve(defaultData);
                      }
                    },
                    fail: (res) => {
                      resolve(defaultData);
                    }
                  });
                } else {
                  resolve(defaultData);
                }
              },
              fail: (err) => {
                resolve(defaultData);
              }
            });
          }
        }
      })
    }
    getLocation();
  })
}
/**
 * 将wx api转为promise 执行
 *  示例 : apiPromise('getUserProfile',{ desc:'获取用户信息' })
 * @param { String } api wx api 名字
 * @param { Object } arg 参数
 * @returns { Promise }
 */
const apiPromise = (api, arg = {}) => {
  return new Promise((resolve, reject) => {
    const success = arg.success
    const fail = arg.success
    arg.success = (...e) => {
      resolve(...e)
      success?.apply(this, ...e)
    }
    arg.fail = (...e) => {
      reject(...e)
      fail?.apply(this, ...e)
    }
    wx[api](arg)
  })
}
/**
 * 循环调用传进来的promise函数
 * @param { Function } handlePromise 被调用的函数,这个函数需要返回一个Promise对象
 * @param { Number } delay 延迟时间
 * @param { Boolean } isExecute 是否立即调用一次
 * @returns { Function } 返回一个停止循环调用的函数
 */
const loopCall = (handlePromise, delay = 300, isExecute = false) => {
  let carrier = null
  if (isExecute) handlePromise();

  function loop() {
    carrier = setTimeout(() => {
      handlePromise().finally(loop)
    }, delay)
  }
  loop()
  return function () {
    clearTimeout(carrier)
    carrier = null
  }
}


module.exports = {
  updateValue,
  vantUpdateValue,
  elementQuery,
  commonNavigateTo,
  getPrevPageData,
  objSerialize,
  dateFormat,
  getTimeStamp,
  getDateDiff,
  lastPage,
  getRequest,
  showLoginLayer,
  commonToPage,
  myNextTick,
  getLocation,
  apiPromise,
  loopCall,
  getQueryUrlPage,
}